package com.gwsdk.paysdk.utils;

import android.content.Context;
import android.content.res.AssetManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 描述：AssetsUtils
 * 作者：钮家齐
 * 时间: 2018-11-09 15:21
 */

public class AssetsUtils {

    private static final String TAG = "AssetsUtils";

    private static AssetsUtils instance;
    private String str;
    private JSONObject jsonObject;

    public static AssetsUtils getInstance() {
        if (null == instance) {
            instance = new AssetsUtils();
        }
        return instance;
    }

    public String getGameID(Context context){
        return Analysis(context,"gameid");
    }

    public String getGameName(Context context){
        return Analysis(context,"gamename");
    }

    public String getGameAppID(Context context){
        return Analysis(context,"gameappid");
    }

    public String getGameKey(Context context){
        return Analysis(context,"access_key");
    }

    public String getGameUrl(Context context){
        return Analysis(context,"gameurl");
    }

    private String Analysis(Context context, String string){
        if(str == null){
            str = getStr(context);
            GWLog.e(TAG,"读取信息："+ str);
        }
        try {
            if (jsonObject != null) {
                return jsonObject.getString(string);
            }
            jsonObject = new JSONObject(str);
            return jsonObject.getString(string);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        GWLog.e(TAG,"游戏参数读取失败");
        return "";
    }

    private String getStr(Context context) {
        AssetManager manager = context.getResources().getAssets();
        try {
            InputStream inputStream = manager.open("gw_config.txt");
            InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String length;
            while ((length = br.readLine()) != null) {
                sb.append(length + "\n");
            }
            //关流
            br.close();
            isr.close();
            inputStream.close();

            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        GWLog.e(TAG,"游戏参数文件读取失败，请参阅对接文档，检查参数文件路径配置是否正确");
        return "";
    }

}
